<template>
  <div id="userRegisterView">
    <h2 style="margin-bottom: 16px">用户注册</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item
        field="userAccount"
        label="账号"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <a-input v-model="form.userAccount" placeholder="请输入账号" />
      </a-form-item>

      <!-- 新增昵称输入行 -->
      <a-form-item
        field="userName"
        label="昵称"
        :rules="[
          { required: true, message: '请输入昵称' },
          { maxLength: 20, message: '昵称长度不能超过20个字符' },
        ]"
      >
        <a-input v-model="form.userName" placeholder="请输入昵称" />
      </a-form-item>

      <a-form-item
        field="userPassword"
        label="密码"
        :rules="[
          { required: true, message: '请输入密码' },
          { minLength: 8, message: '密码长度不能少于8位' },
        ]"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        field="checkPassword"
        label="确认密码"
        :rules="[
          { required: true, message: '请再次输入密码' },
          { validator: validatePassword },
        ]"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="请再次输入密码"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px">
          注册
        </a-button>
        <a-button
          type="outline"
          style="width: 120px; margin-left: 16px"
          @click="router.push('/user/login')"
        >
          返回登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserRegisterRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userName: "", // 新增昵称字段
  userPassword: "",
  checkPassword: "",
} as UserRegisterRequest);

const router = useRouter();

/**
 * 验证两次密码是否一致
 */
const validatePassword = (value: string, callback: any) => {
  if (value !== form.userPassword) {
    callback("两次输入的密码不一致");
  } else {
    callback();
  }
};

/**
 * 提交表单
 */
const handleSubmit = async () => {
  console.log("提交数据:", JSON.stringify(form, null, 2));
  const res = await UserControllerService.userRegisterUsingPost(form);
  if (res.code === 0) {
    message.success("注册成功");
    router.push({
      path: "/user/login",
      replace: true,
    });
  } else {
    message.error("注册失败，" + res.message);
  }
};
</script>
